<template>
  <j-modal
    switchFullscreen
    :width='800'
    :title='title'
    :visible='visible'
    @cancel='handleCancel'
    @ok='handleOk'

    :confirmLoading='confirmLoading'
  >
    <template slot='footer'>
      <a-button @click='handleCancel'>取消</a-button>
      <a-button @click='handleOk' type='primary' v-if='!disableSubmit'>确认</a-button>
    </template>
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-row :gutter='24'>
          <!--       <a-col :span="10">-->
          <div>
            <div style='display: flex;flex-wrap: wrap'>
              <a-form-item
                style='flex: 1'
                :labelCol='{  xs: { span: 10 },sm: { span:6},}'
                :wrapperCol='{ xs: { span:10 }, sm: { span: 17}}'
                label='公告标题'
              >
                <a-input :disabled='disableSubmit' placeholder='请输入公告标题'
                         v-decorator="['title', validatorRules.title]"/>
              </a-form-item>
              <!--       </a-col>-->
              <!--       <a-col :span="10">-->
              <a-form-item
                style='flex: 1'
                :labelCol='{  xs: { span: 10 },sm: { span: 6 },}'
                :wrapperCol='{ xs: { span:10 }, sm: { span: 17}}'
                label='有效时间'
              >
                <a-range-picker
                  :placeholder="['开始时间','结束时间']"
                  :format="'YYYY-MM-DD'"
                  :valueFormat="'YYYY-MM-DD'"
                  v-decorator="['dataRange', validatorRules.dataRange]"
                  @change='dateRangeChange'
                  :disabled='disableSubmit'
                />
              </a-form-item>
            </div>
            <div style='display: flex;flex-wrap: wrap'>
              <!--       </a-col>-->
              <!--       <a-col :span="24">-->
              <a-form-item
                :labelCol='{  xs: { span: 10 },sm: { span:6},}'
                :wrapperCol='{ xs: { span:10 }, sm: { span: 17}}'
                label='公告类型'
                style='flex: 1'
              >
                <cn-dict-select-tag
                  v-decorator="[ 'noticeType', validatorRules.noticeType]"
                  dict-code="notice_type"
                  placeholder="请选择"
                  :disabled='disableSubmit'
                  triggerChange/>
              </a-form-item>
              <a-form-item
                :labelCol='{  xs: { span: 10 },sm: { span:6},}'
                :wrapperCol='{ xs: { span:10 }, sm: { span: 17}}'
                label='是否置顶'
                style='flex: 1'
              >
                <cn-dict-select-tag
                  v-decorator="[ 'isTop', validatorRules.isTop]"
                  dict-code="notice_istop"
                  placeholder="请选择"
                  :disabled='disableSubmit'
                  triggerChange/>
              </a-form-item>
            </div>
              <div style='display: flex;flex-wrap: wrap'>
                <a-form-item
                  :labelCol='{  xs: { span: 10 },sm: { span:6},}'
                  :wrapperCol='{ xs: { span:10 }, sm: { span: 17}}'
                  label="是否小程序"
                  style='flex: 1'
                >
                  <cn-dict-select-tag
                    v-decorator="[ 'isApplets', validatorRules.isTop]"
                    dict-code="announ_small"
                    placeholder="请选择"
                    :disabled='disableSubmit'
                    triggerChange/>
                </a-form-item>
              <a-form-item
                :labelCol='{  xs: { span: 10 },sm: { span:6},}'
                :wrapperCol='{ xs: { span:10 }, sm: { span: 17}}'
                label="是否商城公告"
                style='flex: 1'
              >
                <cn-dict-select-tag
                  v-decorator="[ 'isWeb', validatorRules.isTop]"
                  dict-code="announ_mall"
                  placeholder="请选择"
                  :disabled='disableSubmit'
                  triggerChange/>
              </a-form-item>
            </div>
            <a-form-item
              style='width: 776px'
              :labelCol='{  xs: { span: 24 },sm: { span: 3 },}'
              :wrapperCol='{ xs: { span: 12 }, sm: { span: 21 }}'
              label='公告详情'
            >
              <a-textarea style='height: 80px' :maxLength='500' placeholder='请输入详情'
                          v-decorator="['remarks',validatorRules.remarks]" :disabled='disableSubmit'/>
            </a-form-item>
            <!--       </a-col>-->
            <a-col>
              <a-form-item
                :labelCol='{  xs: { span: 24 },sm: { span: 3 },}'
                :wrapperCol='{ xs: { span: 12 }, sm: { span: 18 }}'
                label='添加附件'
              >
                <!--           <j-upload  accept='.png,.jpg,.jpeg' fileType='image'-->
                <!--                     class='avatar-uploader'-->
                <!--                     :number='1' text='轮播图'-->
                <!--                     :returnUrl='true'></j-upload>-->
                <JUpload ref='hupload' v-bind='loadDatas' :disabled='disableSubmit' :oldList='fileList' @change='handleUpload'
                         :buttonVisible='true'></JUpload>
                <div style='font-size: 14px;color: #979696'>支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div>
              </a-form-item>
            </a-col>
          </div>
        </a-row>
      </a-form>
    </a-spin>
    <a-divider style='font-weight: 600;margin-top: 0px;' orientation='left'>公告可看范围</a-divider>
    <a-tabs ref='tabs' defaultActiveKey='1' @change='cutType'>
      <a-tab-pane tab='组织' key='1'></a-tab-pane>
      <a-tab-pane key='2' tab='角色'></a-tab-pane>
    </a-tabs>
    <div style='width:90%;margin-left:5%;max-height: 400px;border: 1px solid #F1F1F1'>
      <div>
        <a-button v-if='!disableSubmit' style='margin: 10px 30px 0px 30px;' type='primary' @click='handleAdd'>新增</a-button>
        <!--        <a-button style='margin: 10px 30px 0px 0px;' type='primary' @click=''>删除</a-button>-->
      </div>

      <div style='padding: 10px 20px;width: 80%'>
        <a-table
          ref='table'
          size='middle'
          bordered
          rowKey='id'
          :columns='showType?columns2: columns'
          :dataSource='showType?dataSource2:dataSource'
          :pagination='showType?ipagination2:ipagination'
          :loading='loading'
          :scroll='{x:400,y:240 }'
          :rowSelection='{selectedRowKeys:showType? selectedRowKeys2:selectedRowKeys, onChange: onSelectChange}'
          @change='handleTableChange'>
        <span slot='action' slot-scope='text, record'>
           <a :disabled='disableSubmit' style='color: red;' @click='handleDelete(record)'>删除</a>
        </span>
        </a-table>
      </div>
    </div>
    <my-shuttle-modal
      ref='orgShuttleModal'
      title='选择组织'
      :searchConfig='orgSearchConfig'
      :columns='orgColumns'
      :columns2='orgColumns2'
      leftUrl='/cnOrgController/findTreeList'
      keyVal='orgCode'
      @chooseOk='chooseOk'
    ></my-shuttle-modal>
    <my-shuttle-modal
      ref='cusShuttleModal'
      keyVal='roleCode'
      leftUrl='/cnRoleController/getRoleList'
      :searchConfig='cusSearchConfig'
      :columns='cusColumns'
      :columns2='cusColumns2'
      title='选择角色'
      @chooseOk='chooseOk2'
    ></my-shuttle-modal>
    <!--    <proChose ref="prochoose" @okbro="okbropro"></proChose>-->
  </j-modal>
</template>

<script>
import { pick } from 'lodash'
import JUpload from '../../../../components/cn-form/JUpload'
import { getAction, postAction } from '@/api/manage'
import myShuttleModal from '../../../../components/cn-components/CnShuttleModal'
import HUpload from '@/components/cn-components/Hupload'
import { PageListMixin } from '@/mixins/PageListMixin'

export default {
  name: 'cusproModal',
  mixins: [PageListMixin],
  components: { myShuttleModal, HUpload, JUpload },
  data() {
    return {
      disableSubmit: false,
      disableSubmits: false,
      title: '',
      showType: 0,
      dataRange: '',
      orgSearchConfig: [
        {
          type: 'input',
          name: 'orgCode',
          placeholder: '组织编号'
        },
        {
          type: 'input',
          name: 'orgName',
          placeholder: '组织名称'
        }
      ],
      cusSearchConfig: [
        {
          type: 'input',
          name: 'roleCode',
          placeholder: '角色编号'
        },
        {
          type: 'input',
          name: 'roleName',
          placeholder: '角色名称'
        }
      ],
      orgColumns: [

        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'orgCode'
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'orgName'
        }
      ],
      orgColumns2: [
        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'orgCode'
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'orgName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      cusColumns: [
        {
          title: '角色编号',
          align: 'center',
          dataIndex: 'roleCode'
        },
        {
          title: '角色名称',
          align: 'center',
          dataIndex: 'roleName'
        }
      ],
      cusColumns2: [
        {
          title: '角色编号',
          align: 'center',
          dataIndex: 'roleCode'
        },
        {
          title: '角色名称',
          align: 'center',
          dataIndex: 'roleName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      confirmLoading: false,
      form: this.$form.createForm(this),
      visible: false,
      /* 数据源 */
      dataSource: [],
      dataSource2: [],
      fileList: [],
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      selectedRowKeys2: [],
      /* table选中records*/
      selectionRows2: [],
      loadDatas: {
        actionUrl: window._CONFIG['domianUploadURL'] + '/cnUploadController/uploadOss ',
        text: '上传附件'
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }
      },
      ipagination2: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }
      },
      model: {},
      loading: false,
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      },
      columns: [
        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],

      columns2: [
        {
          title: '角色编号',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '角色名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      url: {
        // kuaidi: window._CONFIG['domianOrderURL'] + '/cnDictionaryTypeController/getDictionaryTypeList'
        sendOrder: window._CONFIG['domianURL'] + '/material/saveOrUpdate',
        queryById: '/serviceCentre/cnNotice/getInfo'
      },
      validatorRules: {
        title: {
          rules: [
            { required: true, message: '' }
          ]
        },
        dataRange: {
          rules: [
            { required: true, message: '' }
          ]
        },
        isApplets: {
          rules: [
            { required: true, message: '' }
          ]
        },
        noticeType:{
          rules: [
            { required: true, message: '' }
          ]
        },
        isTop:{
          rules: [
            { required: true, message: '' }
          ]
        },
        remarks: {
          rules: [
            { required: true, message: '' }
          ]
        }
      }
    }

  },
  methods: {
    dateRangeChange(date, name) {
      this.model.startDate = name[0]
      this.model.endDate = name[1]
    },
    cutType(key) {
      if (key == '1') {
        this.showType = false
      } else {
        this.showType = true
      }
    },
    handleAdd() {
      if (this.showType) {
        this.dataSource2.forEach(item => {
          this.$refs.cusShuttleModal.dataSource2.push({ roleName: item.name, roleCode: item.code })
        })
        this.$refs.cusShuttleModal.visible = true
        this.$refs.cusShuttleModal.loadData()
      } else {
        this.dataSource.forEach(item => {
          this.$refs.orgShuttleModal.dataSource2.push({ orgName: item.name, orgCode: item.code })
        })
        this.$refs.orgShuttleModal.visible = true
        this.$refs.orgShuttleModal.loadData()
      }
    },
    add() {

      this.edit()
    },
    edit(isEdit) {
      this.form.resetFields()
      if (isEdit) {
        getAction(this.url.queryById, { id: isEdit.id }).then((res) => {
          if (res.success) {
            let record = res.result
            this.model = Object.assign({}, record)

            this.model.dataRange = []
            if (this.model.startDate && this.model.endDate) {

              this.model.dataRange[0] = this.model.startDate
              this.model.dataRange[1] = this.model.endDate
            }
            if (this.model.noticeScopes) {
              this.model.noticeScopes.forEach(item => {

                if (item.scopeType == 1) {
                  this.dataSource.push(item)
                } else if (item.scopeType == 2) {
                  this.dataSource2.push(item)
                }
              })
            }
            this.fileList = []
            if (this.model.noticeFiles) {
              this.model.noticeFiles.forEach((item, index) => {
                this.fileList.push({ name: item.fileName, url: item.fileUrl, uid: index })
              })
            }

            // console.log(this.fileList)
            // this.$nextTick(() => {
            //   // this.loadData(1)
            //   this.form.setFieldsValue(pick(this.model, 'productGroupName','remarks'))
            // })
            let fieldsVal = pick(this.model, 'title', 'remarks', 'dataRange', 'noticeType','isTop','isWeb','isApplets')
            this.$nextTick(() => {
              this.form.setFieldsValue(fieldsVal)
            })
          }
        })
        console.log(this.model)
      }else{
        this.model={}
      }
    },
    handleDelete(e) {
      if (this.showType) {
        let key = this.dataSource2.map(item => {
          return item.id
        })
        this.dataSource2.splice(key.indexOf(e.id), 1)
      } else {
        let key = this.dataSource.map(item => {
          return item.id
        })
        this.dataSource.splice(key.indexOf(e.id), 1)
      }
    },
    handleUpload(e, e2) {
      this.fileList = e2
    },
    chooseOk(e) {
      let key = this.dataSource.map(item => {
        return item.code
      })
      console.log(e)
      let that = this
      e.forEach(item => {
        if (key.indexOf(item.orgCode) == -1) {
          item.code = item.orgCode
          item.name = item.orgName
          this.dataSource.push(item)
        }
      })


    },
    chooseOk2(e) {
      let key = this.dataSource2.map(item => {
        return item.code
      })
      e.forEach(item => {
        if (key.indexOf(item.roleCode) == -1) {
          item.code = item.roleCode
          item.name = item.roleName
          this.dataSource2.push(item)
        }
      })

    },
    onSelectChange(selectedRowKeys, selectionRows) {
      if (this.showType) {
        this.selectedRowKeys2 = selectedRowKeys
        this.selectionRows2 = selectionRows
      } else {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      }
    },
    handleOk() {
      let that = this

      this.form.validateFields((err, values) => {
        if (!err) {
          that.model.noticeScopes = []
          that.dataSource.forEach(item => {
            that.model.noticeScopes.push({ scopeType: 1, code: item.code, name: item.name })
          })
          that.dataSource2.forEach(item => {
            that.model.noticeScopes.push({ scopeType: 2, code: item.code, name: item.name })
          })

          that.confirmLoading = true
          let formData = Object.assign(that.model, values)

          formData.noticeFiles = []
          that.fileList.forEach(item => {
            formData.noticeFiles.push({ fileName: item.name, fileUrl: item.url })
          })
          // formData.productGroupItems=this.dataSource

          console.log(formData)
          postAction('/serviceCentre/cnNotice/saveOrUpdate', formData).then((res) => {
            if (res.success) {
              that.$message.success(res.message, 2)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.error(res.message, 2)
            }
          }).finally(() => {
            that.confirmLoading = false
          })

        }
      })
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      if (this.ipagination.current !== pagination.current) {
        this.selectionRows = []
        this.selectedRowKeys = []
      }
      this.ipagination = pagination
      // this.loadData()
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
      this.fileList = []
      this.confirmLoading = false
      this.dataSource = []
      this.dataSource2 = []
    },
    close() {
      this.handleCancel()
    }
  }
}
</script>

<style scoped>

</style>
